package com.mlz.mlzmall.ui.activity.frag.main;


import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.ScrollView;
import android.widget.TextView;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;

import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.JsonRequest;
import com.google.gson.Gson;
import com.mlz.mlzmall.R;

import com.mlz.mlzmall.bean.BrandListBean;
import com.mlz.mlzmall.bean.BrandListBean.DataBean;
import com.mlz.mlzmall.bean.GetIndexPromotionResponse;
import com.mlz.mlzmall.bean.PromotionDto;

import com.mlz.mlzmall.ui.activity.act.main.MyApplication;
import com.mlz.mlzmall.ui.activity.act.main.TopicActivity;
import com.mlz.mlzmall.ui.activity.act.personal.PersonalActivity;
import com.mlz.mlzmall.ui.activity.act.personal.ServiceCenterActivity;
import com.mlz.mlzmall.ui.activity.act.personal.myActivityPack.ShareActivity;
import com.mlz.mlzmall.ui.activity.frag.base.BaseFragment;

import com.mlz.mlzmall.ui.dialog.ReuestDialog;
import com.mlz.mlzmall.ui.model.StringTools;
import com.mlz.mlzmall.ui.utils.mlz.ConfigInfo;
import com.mlz.mlzmall.ui.utils.mlz.URL;
import com.mlz.mlzmall.ui.utils.util.LogUtils;
import com.mlz.mlzmall.ui.utils.util.SharedUtils;
import com.mlz.mlzmall.volley.volley.NetRequest;
import com.mlz.mlzmall.volley.volley.RequestListener;
import com.nostra13.universalimageloader.core.ImageLoader;


import org.json.JSONObject;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 功能描述：首页
 * Created by benny on 2016/5/7.
 * ProjectName：mlzMall.
 */
public class HomeFragment extends BaseFragment {

    private ScrollView scrollView;
    private ImageView title_bar;
    private ImageView imageView1;
    private ImageView imageView2;
    private ImageView imageView3;
    private ImageView imageView4;
    private ImageView imageView5;
    private ListView listView;
    private ImageView img_tellCustomerService;
    private ImageView img_getTop;

    private TextView tv_news;
    private LinearLayout one_one;
    private LinearLayout one_two;
    private LinearLayout two;

    List<PromotionDto> promotionDtos;
    List<PromotionDto> nexts;
    public List<DataBean> brandListBeens;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        View view = LayoutInflater.from(getActivity()).inflate(R.layout.fragment_my_home, null);
        initView(view);
        //上部
        getPromotion();
        //下部listview
        getBrandList();
        return view;

    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        // getPromotion();
    }

    private void initView(View view) {
        scrollView = (ScrollView) view.findViewById(R.id.scrollView_qq);
        title_bar = (ImageView) view.findViewById(R.id.iv_tv_title_bar);
        imageView1 = (ImageView) view.findViewById(R.id.picture1);
        imageView2 = (ImageView) view.findViewById(R.id.picture2);
        imageView3 = (ImageView) view.findViewById(R.id.picture3);
        imageView4 = (ImageView) view.findViewById(R.id.picture4);
        imageView5 = (ImageView) view.findViewById(R.id.picture5);
        listView = (ListView) view.findViewById(R.id.lv_main);

        img_tellCustomerService = (ImageView) view.findViewById(R.id.img_msg);
        img_getTop = (ImageView) view.findViewById(R.id.img_up);

        tv_news = (TextView) view.findViewById(R.id.tv_news);
        one_one = (LinearLayout) view.findViewById(R.id.one_one);
        one_two = (LinearLayout) view.findViewById(R.id.one_two);
        two = (LinearLayout) view.findViewById(R.id.two);

        listView = (ListView) view.findViewById(R.id.lv_main);
        title_bar.setOnClickListener(this);
        imageView1.setOnClickListener(this);
        imageView2.setOnClickListener(this);
        imageView3.setOnClickListener(this);
        imageView4.setOnClickListener(this);
        img_tellCustomerService.setOnClickListener(this);
        img_getTop.setOnClickListener(this);

    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.iv_tv_title_bar://这里去个人中心
                startActivity(new Intent(getActivity(), PersonalActivity.class));
                getActivity().overridePendingTransition(R.anim.right_in, R.anim.right_out);
                break;
            case R.id.picture1:
                Intent intent1 = new Intent(getActivity(), TopicActivity.class);
                intent1.putExtra("position", 1);
                SharedUtils.put(getActivity(), "manufacturerId", Integer.valueOf(promotionDtos.get(0).getManufacturerId()));
                SharedUtils.put(getActivity(), "promotionId", Integer.valueOf(promotionDtos.get(0).getPromotionId()));
                startActivity(intent1);
                getActivity().overridePendingTransition(R.anim.in_from_right_back_center, R.anim.out_to_left_back_center);
                break;
            case R.id.picture2:
                Intent intent2 = new Intent(getActivity(), ShareActivity.class);
                StringTools.shareid = 6;
                intent2.putExtra("promotionId", promotionDtos.get(0).getPromotionId());
                //  intent2.putExtra("State",promotionDtos.get(0).get)
                getActivity().startActivity(intent2);
                break;
            case R.id.picture3:
                Intent intent3 = new Intent(getActivity(), TopicActivity.class);
                SharedUtils.put(getActivity(), "manufacturerId", Integer.valueOf(promotionDtos.get(0).getManufacturerId()));
                SharedUtils.put(getActivity(), "promotionId", Integer.valueOf(promotionDtos.get(0).getPromotionId()));
                intent3.putExtra("position", 0);
                startActivity(intent3);
                getActivity().overridePendingTransition(R.anim.in_from_right_back_center, R.anim.out_to_left_back_center);
                break;
            case R.id.picture4:
                Intent intent4 = new Intent(getActivity(), TopicActivity.class);
                intent4.putExtra("position", 2);
                SharedUtils.put(getActivity(), "manufacturerId", Integer.valueOf(promotionDtos.get(0).getManufacturerId()));
                SharedUtils.put(getActivity(), "promotionId", Integer.valueOf(promotionDtos.get(0).getPromotionId()));
                startActivity(intent4);
                getActivity().overridePendingTransition(R.anim.in_from_right_back_center, R.anim.out_to_left_back_center);
                break;
            case R.id.img_msg://去客服中心
                Intent intent5 = new Intent(getActivity(), ServiceCenterActivity.class);
                startActivity(intent5);
                break;
            case R.id.img_up://置顶
                scrollView.scrollTo(0, 0);
                break;
            default:
                showToast("程序错误");
                break;
        }
    }

    /**
     * 判断用户是否登录，若登录保存本地，测试
     */
    public void isUserLogin() {
        if ((Boolean) (SharedUtils.get(getActivity(), "isLogin", false)) == true) {
            NetRequest.get(getActivity(), ConfigInfo.getUrl("http://app.mlzmall.com/mlzmall/api/customer/info", getParamsValue()), new RequestListener() {
                @Override
                public void requestSuccess(String json) {
//                    Gson mgson = new Gson();
//                    CustomerDto mNearDynamic = mgson.fromJson( json, CustomerDto.class);
                    //保存到本地
                    SharedUtils.put(getActivity(), "CustomerDto", json);

                }

                @Override
                public void requestError(VolleyError e) {

                    LogUtils.e("e:" + e.toString());
                }
            });
        }

    }

    /**
     * 请求参数，测试
     */
    private Map<String, String> getParamsValue() {
        Map<String, String> map = new HashMap<>();
        // map.put("telephone", (String) SharedUtils.get(getActivity(),"telephone",""));//获取电话
        map.put("telephone", "18275752650");//获取电话
        return map;
    }


    /**
     * 加载首页图片
     */

    public void getPromotion() {
        ReuestDialog.showProgressDialog(getActivity());
        LogUtils.d("FDGDFGDF");
    //    JsonRequest jsonRequest = new JsonObjectRequest(Request.Method.GET, "http://app.mlzmall.com/api/index/promotion", null, new Response.Listener<JSONObject>() {
            JsonRequest jsonRequest = new JsonObjectRequest(Request.Method.GET, URL.INDEX.PROMOTION, null, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject jsonObject) {
                ReuestDialog.dissmissProgressDialog();
                LogUtils.e("首页品牌" + jsonObject.toString());
                Gson mgson = new Gson();
                GetIndexPromotionResponse getIndexPromotionResponse = mgson.fromJson(jsonObject.toString(), GetIndexPromotionResponse.class);
                promotionDtos = getIndexPromotionResponse.getData().getCurrent();
                nexts = getIndexPromotionResponse.getData().getNext();
                if (null != promotionDtos && !promotionDtos.isEmpty()) {
                    one_one.setVisibility(View.VISIBLE);//后台有数据就显示
                    one_two.setVisibility(View.VISIBLE);

                    ImageLoader.getInstance().displayImage(promotionDtos.get(0).getImage(), imageView1);
                    ImageLoader.getInstance().displayImage(promotionDtos.get(0).getImageSmall(), imageView2);
                    ImageLoader.getInstance().displayImage(promotionDtos.get(0).getManufacturer().getImage(), imageView3);
                    ImageLoader.getInstance().displayImage(promotionDtos.get(0).getManufacturer().getImageSmall(), imageView4);
//
                    //保存共用数据
                    //         SharedUtils.put(getActivity(), "mNum", 1);

//
                } else {
                    one_one.setVisibility(View.GONE);//主图第一行数据后台没有就不显示
                    one_two.setVisibility(View.GONE);
                }
                if (null != nexts && !nexts.isEmpty()) {
                    two.setVisibility(View.VISIBLE);//有数据就显示
                    ImageLoader.getInstance().displayImage(nexts.get(0).getImage(), imageView5);
                    tv_news.setText(nexts.get(0).getDescription());
                } else {
                    two.setVisibility(View.GONE);//后台没有数据就隐藏
                }
                //  showToast(json);

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.e("HFragment_getPromotion", error.getMessage(), error);

            }
        }) {
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                Map<String, String> map = new HashMap<String, String>();
                map.put(ConfigInfo.CHARSET, ConfigInfo.UTF8);
                map.put(ConfigInfo.COOKIE, ConfigInfo.COOKIE_KEY + sessionId);
                map.put(ConfigInfo.TYPE, ConfigInfo.TYPE_KEY);
                return map;
            }
        };

        // 设置该请求的标签
        jsonRequest.setTag("HFragment_getPromotion");
        // 将请求添加到队列中
        ((MyApplication) getActivity().getApplication()).getRequestQueue().add(jsonRequest);
    }

    /**
     * 获取首页品牌列表
     */
    public void getBrandList() {
        ReuestDialog.showProgressDialog(getActivity());
    //    JsonRequest jsonRequest = new JsonObjectRequest(Request.Method.GET, "http://app.mlzMall.com/api/index/manufacturers", null, new Response.Listener<JSONObject>() {
        JsonRequest jsonRequest = new JsonObjectRequest(Request.Method.GET, URL.INDEX.MANUFACTURERS, null, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject jsonObject) {
                ReuestDialog.dissmissProgressDialog();
                LogUtils.d("获取首页品牌列表" + jsonObject.toString());
                Gson gson = new Gson();
                BrandListBean bean = gson.fromJson(jsonObject.toString(), BrandListBean.class);
                brandListBeens = bean.getData();
//                list = bean.getData();
                if (brandListBeens != null && brandListBeens.size() > 0) {
                    LogUtils.d("brandListBeensbrandListBeens");
                    listView.setAdapter(new PhotosAdapter());
                    setListViewHeightBasedOnChildren(listView);
                }
//                list = bean.getData();
//                showToast(list.get(0).getImageSmall());
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.e("HFragment_getBrandList", error.getMessage(), error);

            }
        }) {
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                Map<String, String> map = new HashMap<String, String>();
                map.put(ConfigInfo.CHARSET, ConfigInfo.UTF8);
                map.put(ConfigInfo.COOKIE, ConfigInfo.COOKIE_KEY + sessionId);
                map.put(ConfigInfo.TYPE, ConfigInfo.TYPE_KEY);
                return map;
            }
        };

        // 设置该请求的标签
        jsonRequest.setTag("HFragment_getBrandList");
        // 将请求添加到队列中
        ((MyApplication) getActivity().getApplication()).getRequestQueue().add(jsonRequest);
    }

    //主界面ListView的适配显示
    class PhotosAdapter extends BaseAdapter {
        @Override
        public int getCount() {
            return brandListBeens.size();
        }

        @Override
        public Object getItem(int position) {
            return brandListBeens.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null) {
                convertView = LayoutInflater.from(getActivity()).inflate(R.layout.main_item, null);
                ViewHolder vh = new ViewHolder();
                vh.picture7 = (ImageView) convertView.findViewById(R.id.picture7);
                vh.picture8 = (ImageView) convertView.findViewById(R.id.picture8);
                vh.three = (LinearLayout) convertView.findViewById(R.id.ll_three);//其他品牌第一行图片
                convertView.setTag(vh);
            }
            ViewHolder vHolder = (ViewHolder) convertView.getTag();
            vHolder.three.setVisibility(View.VISIBLE);//有数据就显示
            ImageLoader.getInstance().displayImage(brandListBeens.get(0).getImage(), vHolder.picture7);
            ImageLoader.getInstance().displayImage(brandListBeens.get(0).getImageSmall(), vHolder.picture8);
            vHolder.picture7.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    LogUtils.d(" vHolder.picture7");
                    Intent intent5 = new Intent(getActivity(), TopicActivity.class);
                    SharedUtils.put(getActivity(), "manufacturerId", Integer.valueOf(brandListBeens.get(0).getManufacturerId()));
                    intent5.putExtra("position", 0);
                    startActivity(intent5);
                    getActivity().overridePendingTransition(R.anim.in_from_right_back_center, R.anim.out_to_left_back_center);
                }
            });
            //   vHolder.picture7.setOnClickListener(HomeFragment.this);
            vHolder.picture8.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    LogUtils.d(" vHolder.picture8");
                    Intent intent6 = new Intent(getActivity(), TopicActivity.class);
                    SharedUtils.put(getActivity(), "manufacturerId", Integer.valueOf(brandListBeens.get(0).getManufacturerId()));
                    intent6.putExtra("position", 2);
                    startActivity(intent6);
                    getActivity().overridePendingTransition(R.anim.in_from_right_back_center, R.anim.out_to_left_back_center);
                }
            });
            return convertView;
        }

        class ViewHolder {
            ImageView picture7;
            ImageView picture8;
            LinearLayout three;

        }
    }

    private void setListViewHeightBasedOnChildren(ListView lv_assess) {
        // 获取ListView对应的Adapter
        ListAdapter listAdapter = lv_assess.getAdapter();
        if (listAdapter == null) {
            return;
        }
        int totalHeight = 0;
        for (int i = 0; i < listAdapter.getCount(); i++) {
            // listAdapter.getCount()返回数据项的数目
            View listItem = listAdapter.getView(i, null, lv_assess);
            // 计算子项View 的宽高
            listItem.measure(0, 0);
            // 统计所有子项的总高度
            totalHeight += (listItem.getMeasuredHeight() + lv_assess.getDividerHeight()) + 5;
        }

        ViewGroup.LayoutParams params = lv_assess.getLayoutParams();
        params.height = totalHeight + (lv_assess.getDividerHeight() * listAdapter.getCount());
        // listView.getDividerHeight()获取子项间分隔符占用的高度
        // params.height最后得到整个ListView完整显示需要的高度
        lv_assess.setLayoutParams(params);
    }
}
